package edu.tjpu.share.newui;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.androidpn.client.NotificationService;
import org.androidpn.client.ServiceManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView.BufferType;
import android.widget.Toast;
import edu.tjpu.share.R;
import edu.tjpu.share.app.Fields;
import edu.tjpu.share.po.Server;
import edu.tjpu.share.util.NetworkUtil;

public class Welcome extends Activity {

	private EditText host_ip;
	private EditText host_port;
	private Button btn_save;
	private RadioButton btn_login;
	private RadioButton btn_register;
	private Server serverinfo;
	private boolean issaved;
	private SharedPreferences share;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcom);
		
		host_ip = (EditText) findViewById(R.id.host_ip);
		host_port = (EditText) findViewById(R.id.host_port);
		btn_save = (Button) findViewById(R.id.save_host);
		btn_login = (RadioButton) findViewById(R.id.btn_login);
		btn_register = (RadioButton) findViewById(R.id.btn_register);
		serverinfo = new Server();
		issaved = false;

		btn_save.setOnClickListener(new saveServerInfo());
		btn_login.setOnClickListener(new loginListener());
		btn_register.setOnClickListener(new registerListerner());

		share = Welcome.this.getSharedPreferences("perference", MODE_PRIVATE);
		String hoststr;
		int portnum;

		issaved = share.getBoolean(Fields.IS_HOST_SAVED, false);

		if (issaved) {
			hoststr = share.getString(Fields.HOST, "");// 根据key寻找值 参数1 key 参数2
														// 如果没有value显示的内容
			portnum = share.getInt(Fields.PORT, 8080);
			host_ip.setText(hoststr, BufferType.NORMAL);
			host_port.setText(portnum + "", BufferType.NORMAL);
			serverinfo.setHost(hoststr);
			serverinfo.setProt(portnum);
			//开启推送
			ServiceManager serviceManager = new ServiceManager(Welcome.this);
			serviceManager.setNotificationIcon(R.drawable.logo);
			serviceManager.startService();
			
			
			Intent intent = new Intent("org.androidpn.client.NotificationService");
			intent.setAction("org.androidpn.client.NotificationService");
			intent.setClass(Welcome.this, NotificationService.class);
			startService(intent);
			//开启推送
		}
	}

	class saveServerInfo implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (host_ip.getText().toString().trim() != null
					&& !"".equals(host_ip.getText().toString().trim())
					&& host_port.getText().toString().trim() != null
					&& !"".equals(host_port.getText().toString().trim())
					&& (isIp(host_ip.getText().toString().trim()) || isUrl(host_ip
							.getText().toString().trim()))
					&& isport(Integer.parseInt(host_port.getText().toString()
							.trim()))) {

				serverinfo = new Server();
				serverinfo.setHost(host_ip.getText().toString().trim());
				serverinfo.setProt(Integer.parseInt(host_port.getText()
						.toString().trim()));

				Editor editor = share.edit();// 取得编辑器
				editor.putInt(Fields.PORT, serverinfo.getProt());
				editor.putString(Fields.HOST, serverinfo.getHost());// 存储配置 参数1
																	// 是key 参数2
																	// 是值
				editor.putString(Fields.USER_NAME, "");
				editor.putString(Fields.USER_PASSWD, "");
				editor.putString(Fields.USER_AVATAR, "");

				
				editor.putBoolean(Fields.IS_HOST_SAVED, true);

				editor.commit();// 提交刷新数据
				
				if(!issaved){
					//开启推送
					ServiceManager serviceManager = new ServiceManager(Welcome.this);
					serviceManager.setNotificationIcon(R.drawable.logo);
					serviceManager.startService();
					
					
					Intent intent = new Intent("org.androidpn.client.NotificationService");
					intent.setAction("org.androidpn.client.NotificationService");
					intent.setClass(Welcome.this, NotificationService.class);
					startService(intent);
					//开启推送
				}
				issaved = true;

				Toast.makeText(Welcome.this, "保存成功！", Toast.LENGTH_SHORT)
						.show();
				Toast.makeText(Welcome.this, "用户登录信息已删除！", Toast.LENGTH_SHORT)
						.show();
			} else {
				Toast.makeText(Welcome.this, "请填写正确数据后再保存！", Toast.LENGTH_SHORT)
						.show();
			}
		}

	}

	class loginListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			if (!NetworkUtil.isAccessToInternet(Welcome.this)) {
				new AlertDialog.Builder(Welcome.this)
				.setTitle("没有网络连接！")
				.setMessage("您要进入设置界面吗？")
				.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
							}
						})
				.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");  
								startActivity(wifiSettingsIntent);
							}
						}).show();
			} else {
				if (issaved) {
					Intent intent = new Intent();
					Bundle bundle = new Bundle();
					bundle.putSerializable(Fields.SERVER_INFO, serverinfo);
					intent.putExtras(bundle);
					intent.setClass(Welcome.this, Login.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					//finish();
				} else {
					Toast.makeText(Welcome.this, "请先保存服务器信息后再试！",
							Toast.LENGTH_SHORT).show();
				}
			}
		}

	}

	class registerListerner implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (!NetworkUtil.isAccessToInternet(Welcome.this)) {
				new AlertDialog.Builder(Welcome.this)
				.setTitle("没有网络连接！")
				.setMessage("您要进入设置界面吗？")
				.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
							}
						})
				.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");  
								startActivity(wifiSettingsIntent);
							}
						}).show();
			} else {
				if (issaved) {
					Intent intent = new Intent();
					Bundle bundle = new Bundle();
					bundle.putSerializable(Fields.SERVER_INFO, serverinfo);
					bundle.putSerializable(Fields.IS_REG, true);
					intent.putExtras(bundle);
					intent.setClass(Welcome.this, GetAcademy.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 清除该进程空间的所有Activity
					startActivity(intent);
					//finish();
				} else {
					Toast.makeText(Welcome.this, "请先保存服务器信息后再试！",
							Toast.LENGTH_SHORT).show();
				}
			}
		}

	}

	public boolean isIp(String ipAddress) {
		String ip = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
		Pattern pattern = Pattern.compile(ip);
		Matcher matcher = pattern.matcher(ipAddress);
		return matcher.matches();
	}

	public boolean isUrl(String url) {
		String urlpattern = "([a-za-z0-9.]?([0-9a-za-z][0-9a-za-z-]+.)+[a-za-z]{2,5})|((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]))";
		Pattern pattern = Pattern.compile(urlpattern);
		Matcher matcher = pattern.matcher(url);
		return matcher.matches();
	}

	public boolean isport(int isport) {
		if (isport < 1 || isport > 65535)
			return false;
		else
			return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.general_option_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.about:
			// 关于Share

			break;
		case R.id.logout:
			// 退出Share
			finish();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		// 按下键盘上返回按钮
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			new AlertDialog.Builder(this)
					.setTitle("警告")
					.setMessage("您确定要退出吗？")
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							})
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									finish();
								}
							}).show();

			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

}
